from os import system, mkdir
from fix import reconnectDevice
from sendEmail import sendOfflineError
from devices import devicesIP, updateDeviceLastScreen
from pacc.adb import getOnlineDevices
from datetime import datetime
from os.path import exists
from picture import isSamePic
from PIL import Image, UnidentifiedImageError
from config import pictureRoot


pCnt = 0


def mkDevicesDir(deviceName):
    pictureDir = '%s/%s' % (pictureRoot, deviceName)
    if not exists(pictureDir):
        mkdir(pictureDir)


def getScreen(deviceName):
    mkDevicesDir(deviceName)
    dIP = devicesIP[deviceName]
    if dIP not in getOnlineDevices(): reconnectDevice(deviceName)
    if dIP not in getOnlineDevices():
        sendOfflineError(deviceName)
        return
    pPath = '%s/%s/%s.png' % (pictureRoot, deviceName, datetime.now().strftime("%Y_%m_%d %H-%M-%S.%f")[:-3])
    system('adb -s %s exec-out screencap -p > "%s"'
           % (dIP, pPath))
    global pCnt
    pCnt += 1
    oldPPath = updateDeviceLastScreen(deviceName, pPath)
    print(pCnt, pPath)
    try:
        img = Image.open(pPath)
        # print(img.size)
        cropped = img.crop((60, 960, 1020, 1780))  # (left, upper, right, lower)
        cropped.save(pPath)
        return isSamePic(oldPPath, pPath)
    except (UnidentifiedImageError, FileNotFoundError, PermissionError) as e:
        print(e)
        return True

